package ynu.edu.online_course.mapper;

import org.apache.ibatis.annotations.*;
import ynu.edu.online_course.entity.UserRole;
import java.util.List;

@Mapper
public interface UserRoleMapper {

    // 根据用户ID查询角色列表
    @Select("SELECT ur.user_id, ur.role_id, ur.assigned_at, " +
            "u.id AS user_id, u.username AS user_name, " +
            "r.id AS role_id, r.role_name AS role_name " +
            "FROM user_role ur " +
            "JOIN user u ON ur.user_id = u.id " +
            "JOIN role r ON ur.role_id = r.id " +
            "WHERE ur.user_id = #{userId}")
    @Results({
            @Result(property = "id.userId", column = "user_id"),
            @Result(property = "id.roleId", column = "role_id"),
            @Result(property = "assignedAt", column = "assigned_at"),
            @Result(property = "user.id", column = "user_id"),
            @Result(property = "user.username", column = "user_name"),
            @Result(property = "role.id", column = "role_id"),
            @Result(property = "role.roleName", column = "role_name")
    })
    List<UserRole> findRolesByUserId(@Param("userId") Long userId);




    // 插入用户角色关系
    @Insert("INSERT INTO user_role (user_id, role_id) VALUES (#{user.id}, #{role.id})")
    int insertUserRole(UserRole userRole);

    // 删除用户角色关系
    @Delete("DELETE FROM user_role WHERE user_id = #{userId} AND role_id = #{roleId}")
    int deleteUserRole(@Param("userId") Long userId, @Param("roleId") Long roleId);

    @Select("SELECT COUNT(*) FROM user_role ur " +
            "JOIN role r ON ur.role_id = r.id " +
            "WHERE ur.user_id = #{userId} AND r.id = 3")
    boolean isAdmin(@Param("userId") Long userId);

}
